package mbean;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Properties;

import util.FacesUtil;

public class NavigationMBean {
	
	private String telaAtual, metodo, mbean, beanTelaAtual;
	private boolean validaSalvar, openError;
	private Properties classes;
	
	public NavigationMBean(){
		this.classes = new Properties();
		try {
			this.classes.load(this.getClass().getResourceAsStream("/util/mapeamentoClasseBean.properties"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String navega(){
		Method method;
		String retorno = "";
		this.openError = false;
		
		try{
			Object bean = FacesUtil.getSessionMapValue(this.mbean);
			
			if (bean == null){
				if (! this.mbean.equalsIgnoreCase("")){
					String classe = this.classes.getProperty(this.mbean);
					Class<?> cls = Class.forName(classe);
					Constructor<?> ct = cls.getConstructor(null);
					bean = ct.newInstance(null);
					FacesUtil.setSessionMapValue(this.mbean, bean);
				}
			}
			
			if (this.validaSalvar){
				Object beanTelaAtual = FacesUtil.getSessionMapValue(this.beanTelaAtual);
				method = beanTelaAtual.getClass().getMethod("isDirty", null);
				Boolean dirty = (Boolean) method.invoke(beanTelaAtual, null);
				
				if (dirty){
					this.openError = true;
				}
				else{
					retorno = redirecionaTela(bean);
				}
			}
			else{
				retorno = redirecionaTela(bean);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return retorno;
	}

	private String redirecionaTela(Object bean) {
		try{
			if (! this.mbean.equalsIgnoreCase("")){
				Method method = bean.getClass().getMethod(this.metodo, null);
				return (String) method.invoke(bean, null);
			}
			else
				return "back";
		}
		catch(Exception e){
			e.printStackTrace();
			return "";
		}
	}

	public void setTelaAtual(String telaAtual) {
		this.telaAtual = telaAtual;
	}

	public String getTelaAtual() {
		return telaAtual;
	}

	public void setValidaSalvar(boolean validaSalvar) {
		this.validaSalvar = validaSalvar;
	}

	public boolean getValidaSalvar() {
		return validaSalvar;
	}

	public void setMetodo(String metodo) {
		this.metodo = metodo;
	}

	public String getMetodo() {
		return metodo;
	}

	public void setMbean(String mbean) {
		this.mbean = mbean;
	}

	public String getMbean() {
		return mbean;
	}

	public void setBeanTelaAtual(String beanTelaAtual) {
		this.beanTelaAtual = beanTelaAtual;
	}

	public String getBeanTelaAtual() {
		return beanTelaAtual;
	}

	public void setOpenError(boolean openError) {
		this.openError = openError;
	}

	public boolean getOpenError() {
		return openError;
	}
}
